package com.lewis.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lewis.core.annotation.Log;
import com.lewis.core.base.controller.BaseController;
import com.lewis.core.base.domain.BaseResult;
import com.lewis.core.base.domain.entity.SysUser;
import com.lewis.core.base.domain.model.LoginUser;
import com.lewis.core.base.page.TableDataInfo;
import com.lewis.core.constant.UserConstants;
import com.lewis.core.enums.BusinessType;
import com.lewis.core.utils.SecurityUtil;
import com.lewis.core.utils.ServletUtil;
import com.lewis.core.utils.StringUtil;
import com.lewis.core.utils.office.excel.ExcelUtil;
import com.lewis.system.service.ISysUserService;
import com.lewis.system.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户信息
 *
 * @author Lewis
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

	@Resource
	private ISysUserService sysUserService;

	@Resource
	private TokenService tokenService;

	@ApiOperation(value = "获取用户列表", notes = "获取用户列表")
	@Log(
			title = "用户管理",
			businessType = BusinessType.SELECT
	)
	@GetMapping("/list")
	public TableDataInfo list(SysUser user) {
		startPage();
		return getTableData(sysUserService.selectUserList(user));
	}

	@ApiOperation(value = "导出用户列表", notes = "导出用户列表")
	@Log(
			title = "用户管理",
			businessType = BusinessType.EXPORT
	)
	@GetMapping("/export")
	public BaseResult export(SysUser user) {
		List<SysUser> list = sysUserService.selectUserList(user);
		return new ExcelUtil<>(SysUser.class).exportExcel(list, "用户数据");
	}

	@ApiOperation(value = "导入用户列表", notes = "导入用户列表")
	@Log(
			title = "用户管理",
			businessType = BusinessType.IMPORT
	)
	@PostMapping("/importData")
	public BaseResult importData(MultipartFile file, boolean updateSupport) throws Exception {
		List<SysUser> userList = new ExcelUtil<>(SysUser.class).importExcel(file.getInputStream());
		LoginUser loginUser = tokenService.getLoginUser(ServletUtil.getRequest());
		String operName = loginUser.getUsername();
		String message = sysUserService.importUser(userList, updateSupport, operName);
		return ok().setMsg(message);
	}

	@ApiOperation(value = "导入模板", notes = "导入模板")
	@GetMapping("/importTemplate")
	@Log(
			title = "用户管理",
			businessType = BusinessType.IMPORT
	)
	public BaseResult importTemplate() {
		return new ExcelUtil<>(SysUser.class).importTemplateExcel("用户数据");
	}

	@ApiOperation(value = "根据用户编号获取详细信息", notes = "根据用户编号获取详细信息")
	@GetMapping(value = {"/", "/{userId}"})
	@Log(
			title = "用户管理",
			businessType = BusinessType.SELECT
	)
	public Object getInfo(@PathVariable(value = "userId", required = false) Long userId) {
		return StringUtil.isNotNull(userId)
				? ok().setData(sysUserService.getOne( new LambdaQueryWrapper<SysUser>() .eq(SysUser::getId, userId)))
				: fail();
	}

	@ApiOperation(value = "新增用户", notes = "新增用户")
	@Log(
			title = "用户管理",
			businessType = BusinessType.INSERT
	)
	@PostMapping
	public BaseResult add(@Validated @RequestBody SysUser user) {
		if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUserName()))) {

			return fail().setMsg("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
		}

		if (StringUtil.isNotEmpty(user.getPhoneNumber())
				&& UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {

			return fail().setMsg("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
		}

		if (StringUtil.isNotEmpty(user.getEmail())
				&& UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))) {

			return fail().setMsg("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}

		user.setCreateBy(SecurityUtil.getUsername());
		user.setPassword(SecurityUtil.encryptPassword(user.getPassword()));
		return getResult(sysUserService.insertUser(user));
	}

	@ApiOperation(value = "修改用户", notes = "修改用户")
	@Log(
			title = "用户管理",
			businessType = BusinessType.UPDATE
	)
	@PutMapping
	public BaseResult edit(@Validated @RequestBody SysUser user) {
		sysUserService.checkUserAllowed(user);
		if (StringUtil.isNotEmpty(user.getPhoneNumber())
				&& UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))) {

			return fail().setMsg("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
		}

		if (StringUtil.isNotEmpty(user.getEmail())
				&& UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))) {

			return fail().setMsg("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		user.setUpdateBy(SecurityUtil.getUsername());

		return getResult(sysUserService.updateUser(user));
	}

	@ApiOperation(value = "删除用户", notes = "删除用户")
	@Log(
			title = "用户管理",
			businessType = BusinessType.DELETE
	)
	@DeleteMapping("/{ids}")
	public BaseResult remove(@PathVariable Long[] ids) {
		return getResult(sysUserService.deleteUserByIds(ids));
	}

	@ApiOperation(value = "重置密码", notes = "重置密码")
	@Log(
			title = "用户管理",
			businessType = BusinessType.UPDATE
	)
	@PutMapping("/resetPwd")
	public BaseResult resetPwd(@RequestBody SysUser user) {
		sysUserService.checkUserAllowed(user);
		user.setPassword(SecurityUtil.encryptPassword(user.getPassword()));
		user.setUpdateBy(SecurityUtil.getUsername());
		return getResult(sysUserService.resetPwd(user));
	}

	@ApiOperation(value = "状态修改", notes = "状态修改")
	@Log(
			title = "用户管理",
			businessType = BusinessType.UPDATE
	)
	@PutMapping("/changeStatus")
	public BaseResult changeStatus(@RequestBody SysUser user) {
		sysUserService.checkUserAllowed(user);
		user.setUpdateBy(SecurityUtil.getUsername());
		return getResult(sysUserService.updateUserStatus(user));
	}
}
